package com.tupu.controller.permission;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tupu.common.Result;
import com.tupu.util.ValidateCodeUtil;
import com.tupu.entity.permission.UserInfo;
import com.tupu.entity.dto.UserDto;
import com.tupu.service.permission.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 首页登录
 */

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private ValidateCodeUtil validateCodeUtil;

    /**
     * 用户登录
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result userLogin(HttpServletRequest request,
                            @RequestBody(required = false) UserInfo user) {
        try {
            if (!validateCodeUtil.checkCode(user.getValidatecode(), user.getCodeId())) {
                return Result.errorMessage("验证码错误！");
            }
            String result = userService.testUser(user);
            if (!result.equals("账号正常")) {
                return Result.errorMessage(result);
            } else {
                Map<String, Object> map = userService.userLogin(request, user);
                return Result.ok(map);
            }
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/getValidateCode")
    public Result getValidateCode(HttpServletRequest request, @RequestParam String clientUID) {
        String imgBase64 = validateCodeUtil.getRandomCodeImage(request, clientUID);
        if (StringUtils.isNotEmpty(imgBase64)) {
            return Result.ok(imgBase64);
        }
        return Result.errorMessage("获取验证码失败！");
    }

    /**
     * 用户 登出
     *
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public Result logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return Result.ok("退出成功");
    }

    @RequestMapping("/info")
    public Result<Map<String, Object>> info(String account) {
        Map<String, Object> map = new HashMap<>();
        try {
            map = userService.info(account);
            return Result.ok(map);
        } catch (Exception e) {
            map.put("错误信息", e.getMessage());
            return Result.error(map);
        }
    }

   /* @PostMapping("/info")
    public Result getUserInfo(HttpServletRequest request) {
        String token = tokenUtils.getToken(request);
           /* // 对 token 进行校验
            if(StringUtils.isEmpty(token)) { // 如果没有获取到 Token
                result.put(-1, "没有获取到 Token, 请求被阻止");
            } else if(!Constant.AUTHOR.equals(Token.getIssuer(token))) { // 如果 Token 的签发人不正确
                result.put(-2, "非法的 Token, 请求被阻止");
            } else if(Token.checkTokenExpired(token)) { // 如果 Token 已过期
                result.put(-3, "过期的 Token, 请求被阻止");
            } else {
                String userId = Token.getSubject(token);
                User user = userService.getUserById(userId);
                result.put(0, user);
            }
            return result;
        return Result.ok(token);
    }*/

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody(required = false) UserInfo user) {
        try {
            userService.register(user);
            return Result.ok("注册成功");
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 上传头像图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Map<String, Object> UploadPicture(@RequestParam(required = false) MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            result = userService.UploadPicture(file);
            return result;
        } catch (Exception e) {
            result.put("错误信息", e.getMessage());
            return result;
        }
    }

    /**
     * 用户页列表展示 分页 名称模糊搜索
     *
     * @param page
     * @param size
     * @param user_name
     * @return
     */
    @PostMapping("/list")
    public Result<Page<UserDto>> findByPage(@RequestParam(required = false, defaultValue = "1") Integer page,
                                            @RequestParam(required = false, defaultValue = "10") Integer size,
                                            @RequestParam(required = false) String user_name,
                                            @RequestParam(required = false) List<Integer> statusList) {
        try {
            Page<UserDto> pageDto = userService.pageInfo(page, size, user_name, statusList);
            return Result.ok(pageDto);
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 根据id 查询一条数据
     *
     * @param user_id
     * @return
     */
    @PostMapping("/findOneById")
    public Result<UserDto> findOneByUserId(@RequestParam(required = false) Integer user_id) {
        try {
            UserDto userDto = userService.findOneByUserId(user_id);
            return Result.ok(userDto);
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 添加用户 排重
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result addUser(@RequestBody(required = false) UserInfo user) {
        try {
            String result = userService.addUser(user);
            if (result.equals("添加成功")) {
                return Result.ok("添加成功");
            }
            if (result.equals("账号已存在")) {
                return Result.errorMessage("账号已存在");
            }
            if (result.equals("密码输入不一致")) {
                return Result.errorMessage("密码输入不一致");
            }
            if (result.equals("请输入正确的手机号")) {
                return Result.errorMessage("请输入正确的手机号");
            }
            return Result.errorMessage("新增失败");
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 根据user_id 删除用户（可批量删除）
     *
     * @param ids
     * @return
     */
    @PostMapping("/del")
    public Result delUser(@RequestParam(required = false) List<Integer> ids) {
        try {
            userService.delUser(ids);
            return Result.ok("删除成功");
        } catch (Exception e) {
            return Result.errorMessage("错误信息:" + e.getMessage());
        }
    }

    /**
     * 根据id 更新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    public Result updateUser(@RequestBody(required = false) UserInfo user) {
        try {
            String result = userService.updateUser(user);
            if (result.equals("修改成功")) {
                return Result.ok("修改成功");
            }
            if (result.equals("密码输入不一致")) {
                return Result.errorMessage("密码输入不一致");
            }
            if (result.equals("请输入正确的手机号")) {
                return Result.errorMessage("请输入正确的手机号");
            }
            if (result.equals("登录账号已存在")) {
                return Result.errorMessage("登录账号已存在");
            }
            return Result.errorMessage("修改失败");
        } catch (Exception e) {
            return Result.errorMessage(e.getMessage());
        }
    }

    /**
     * 根据user_id 审批用户
     *
     * @param id
     * @return
     */
    @PostMapping("/approval")
    public Result approvalUser(@RequestParam(required = false) Integer id) {
        try {
            userService.approvalUser(id);
            return Result.ok("审核成功");
        } catch (Exception e) {
            return Result.errorMessage("错误信息:" + e.getMessage());
        }
    }

    /**
     * 查询新增用户个数
     *
     * @return
     */
    @RequestMapping("/userNum")
    public Result<Map<String, Object>> userNum() {
        Map<String, Object> map = new HashMap<>();
        try {
            map = userService.userNum();
            return Result.ok(map);
        } catch (Exception e) {
            map.put("错误信息", e.getMessage());
            return Result.error(map);
        }
    }

    /**
     * 从其他系统登录时调用此方法
     *
     * @param otherToken
     * @return
     */
    @RequestMapping("/loginOther")
    public Result loginOther(@RequestParam String otherToken) {
        try {
            return Result.ok(userService.loginOther(otherToken));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.errorMessage(e.getMessage());
        }
    }
}